export const extend = (target, source, source2) => {
    if (target && source) {
        var value = null;
        for(name in source) {
            value = source[name];
            if(typeof(value) == 'object') {
                if(!target[name] || value instanceof Array) {
                    target[name] = clone(value);
                } else {
                    extend(target[name], value);
                }
            } else {
                target[name] = value;
            }
            
        }
        extend(target, source2);
    }
    return target;
}

export const clone = (json) => {
    var text = JSON.stringify(json);
    return JSON.parse(text);
}

export const format = (s, args) => {
    var keys = args instanceof Array ? args : [args];
    var result = s;
    for(var i=0; i<keys.length; i++) {
        result = result.replace(new RegExp("\\{" +i+ "\\}", "g"), keys[i]);
    }
    return result;
}

export const queueEach = (items, callback) => {
    var keys = Object.keys(items);
    var index = - 1;
    var length = keys.length - 1;
    var isArray = items instanceof Array;
    var iterator = {
        hasNext() {
            return index < length;
        },
        next() {
            index ++;
            var key = keys[index];
            var item = items[key];
            callback.call(this, item, isArray ? index : key);
        }
    };
    iterator.next();
}

export const isBlank = (value) => {
    if(value == undefined) {
        return true;
    }
    if(value == null) {
        return true;
    } 
    if(typeof(value) == 'string' && value == '') {
        return true;
    }
    if(value instanceof Array && value.length == 0) {
        return true;
    }
    return false;
}

export default {
    extend,
    format,
    clone,
    queueEach,
    isBlank
}